import { DOCKLEFT, DOCKRIGHT, HIDETASKPANE, ADDSTRING, GETDOCNAME, SETDEMOSPAN, OPENWEB, ADDBASICSITUATION, OPENDOC } from "../actions/taskpane";
import * as Immutable from "immutable";
import Util from "../js/util.js"
import dataParse from "./parseData";

/* global wps:false */
import { ajaxPrefilter, parseHTML } from "jquery";
const defaultState = Immutable.Map({
    docName: null,
    demoSpan: "waiting...",
    contentControlTitle: ""
});
export default function (state = defaultState, action) {
    switch (action.type) {
        case DOCKLEFT:
            {
                let tsId = wps.PluginStorage.getItem("taskpane_id")
                if (tsId) {
                    let tskpane = wps.GetTaskPane(tsId)
                    let value;
                    if (wps.Enum)
                        value = wps.Enum.msoCTPDockPositionLeft;
                    else
                        value = Util.WPS_Enum.msoCTPDockPositionLeft
                    tskpane.DockPosition = value
                }
                break
            }
        case DOCKRIGHT:
            {
                let tsId = wps.PluginStorage.getItem("taskpane_id")
                if (tsId) {
                    let tskpane = wps.GetTaskPane(tsId)
                    let value;
                    if (wps.Enum)
                        value = wps.Enum.msoCTPDockPositionRight;
                    else
                        value = Util.WPS_Enum.msoCTPDockPositionRight
                    tskpane.DockPosition = value
                }
                break
            }
        case HIDETASKPANE:
            {
                let tsId = wps.PluginStorage.getItem("taskpane_id")
                if (tsId) {
                    let tskpane = wps.GetTaskPane(tsId)
                    tskpane.Visible = false
                }
                break
            }
        case ADDBASICSITUATION: {
            let doc = wps.WpsApplication().ActiveDocument.ContentControls
            doc.Item(6).Range.Paragraphs.Add()
            let last = doc.Item(6).Range.Paragraphs.Count

            let myRange = doc.Item(6).Range.Paragraphs.Item(last).Range
            // //   doc.Item(6).Range.Cut()
            let tlbles = doc.Item(6).Range.Document.Tables.Add(myRange, 5, 5)

            break;
        }
        case OPENDOC: { //在新建的文档里面添加从网上下载的文档的内容
            let doc = wps.WpsApplication()
            let path = wps.OAAssist.DownloadFile("https://cdn.touzhiwang.com/auto_compose/projects/0000047c/init.docx")
            doc.Documents.Open(path) ///下载并打开文档
            let activeDoc = doc.ActiveDocument
            //绑定进入控件输出控件标题
            let func = (doc) => {

                let range = doc.Cells//选中区域表格的列
                let firstRow = range.Item(1).Row.Cells.Item(1)//选中单元格同行第一个单元格内容 
                let firstCol = range.Item(1).Column.Cells.Item(1)
                function getText(range) {
                    let count = range.Range.Words.Count
                    let text = ""
                    for (let index = 1; index < count; index++) {
                        text += range.Range.Words.Item(index).Text
                    }
                    return text
                }
                let RowText = getText(firstRow)
                alert(RowText)
                let colText = getText(firstCol)
                alert(colText)
                //      range.Item(1).Column.Cells.Item(1).Select()




            }
            // activeDoc.ApiEvent.AddApiEventListener("ContentControlOnEnter", func)
            doc.ApiEvent.AddApiEventListener("WindowSelectionChange", func)

            break
        }
        case ADDSTRING:
            {
                let data = wps.FileSystem.ReadFile("C:/Users/yuan/Desktop/data.json")//读取文件拿到json数据
                let doc = wps.WpsApplication().ActiveDocument.ContentControls
                function isnertData(ContentControl, data) {
                    let num = ContentControl
                    let riskTip = parseHTML(data)
                    let result = dataParse(riskTip)
                    result.forEach((item, index) => {
                        if (typeof item == "string") { //如果是字符串，直接添加进文档
                            if (index === 0) { //第一个内容无法使用insertafter
                                doc.Item(num).Range.Text = item
                            } else {
                                doc.Item(num).Range.InsertAfter(item)
                            }
                            if (index !== result.length) {
                                doc.Item(num).Range.Paragraphs.Add()
                            }
                        }
                        else if (item.Blob) {
                            doc.Item(num).Range.InlineShapes.AddPicture(item.Blob.blob)
                        }
                        else { //表格
                            doc.Item(num).Range.Paragraphs.Add()
                            let last = doc.Item(num).Range.Paragraphs.Count
                            let myRange = doc.Item(num).Range.Paragraphs.Item(last).Range
                            let row = item.length
                            let col = 0
                            item.forEach((item) => { //获取二维数组中长度最大的作为表格的
                                if (item.length > col) {
                                    col = item.length
                                }
                            })
                            let tblNew = doc.Item(num).Range.Document.Tables.Add(myRange, row, col)
                            item.forEach((item, index) => {
                                let row = index
                                item.forEach((item, index) => {
                                    tblNew.Cell(row + 1, index + 1).Range.Text = item
                                })
                            })
                            tblNew.Columns.AutoFit()
                            doc.Item(num).Range.Paragraphs.Add()
                        }
                    })
                }

                let num = doc.Count
                data = JSON.parse(data)
                data = data.fields_richtext
                for (let index = 1; index <= num; index++) {
                    let title = doc.Item(index).Tag
                    if (data[title]) {
                        isnertData(index, data[title])
                    }
                }

                break;
            }
        case GETDOCNAME:
            {

                let docName = wps.WpsApplication().ActiveDocument.Name
                let newState = state.set('docName', docName)
                return newState
            }

        case SETDEMOSPAN:
            {
                let newState = state.set('DemoSpan', action.data)
                return newState
            }

        case OPENWEB:
            {
                let param = state.get('demoSpan')
                wps.OAAssist.ShellExecute(param)
            }
        default:
    }
    return state;
}